<?php
namespace Api\Service;

/**
 * 投诉
 */
class ComplaintService
{
    /**
     * 投诉分类
     * @return [type] [description]
     */
    public function lists()
    {
        $complaints = S('complaint');
        if (!$complaints || true) {
            $complaints = M('complaint_category')
                ->order('sort desc, id desc')
                ->getField('name', true);
            S('complaint', $complaints, 3600 * 12); // 12小时
        }
        return $complaints ? $complaints : [];
    }
    /**
     * 投诉订单
     * @param  [type] $order_no [description]
     * @return [type]           [description]
     */
    public function order($user_id, $order_no, $user, $complaint, $images)
    {
        $order = M('order')
            ->field('id,shop_id,is_complaint')
            ->where(['order_no' => $order_no])
            ->find();

        if (!$order || $order['is_complaint']) {
            return false;
        }

        $complaint = [
            'shop_id'  => $order['shop_id'],
            'order_id' => $order['id'],
            'user_id'  => $user_id,
            'username' => $user['username'],
            'mobile'   => $user['mobile'],
            'reason'   => $complaint['reason'],
            'content'  => $complaint['content'],
            'add_time' => CUR_DATETIME,
        ];
        begin();
        $res1 = M('complaint')->add($complaint);

        $res2 = M('order')->where(['order_no' => $order_no])->save([
            'is_complaint' => 1,
        ]);

        $complaint_image = [];
        if (count($images)) {
            foreach ($images as $image) {
                $complaint_image[] = [
                    'complaint_id' => $res1,
                    'image'        => $image,
                    'add_time'     => CUR_DATETIME,
                ];
            }
            M('complaint_image')->addAll($complaint_image);
        }

        if ($res1 && $res2) {
            commit();
            return true;
        } else {
            rollback();
            return false;
        }
    }
}
